const mysql = require("mysql")

var pool

const sqlQuery = (configdb, sql, values) => {
  if (!pool) {
    pool = mysql.createPool(configdb)
  }

  return new Promise((resolve, reject) => {
    pool.getConnection((err, connection) => {
      if (err) {
        reject(err)
      } else {
        if (values) {
          connection.query(sql, values, (err, rows) => {
            if (err) {
              reject(err)
            } else {
              resolve(rows)
            }
            connection.release()
          })
        } else {
          connection.query(sql, (err, rows) => {
            if (err) {
              reject(err)
            } else {
              resolve(rows)
            }
            connection.release()
          })
        }
      }
    })
  })
}

module.exports = { sqlQuery }
